import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Text,
    FlatList,
    Image,
    TouchableOpacity,
    DeviceEventEmitter,
} from 'react-native';

import { RRCLoading, RRCToast } from 'react-native-overlayer';

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import DashLine from './DashLine';
import HttpUtil from '../util/HttpUtil';
import {NavigationEvents} from 'react-navigation';

// const data = [
//     { id:1, name:'IBMX3128服务器', rfid:'AC8231749888', state:'待发卡', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' }, 
//     // { id:2, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:3, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:4, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:5, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:6, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:7, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:8, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:9, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:10, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
// ];

let pageNo = 1; //当前第几页
let totalPage = 0; //总的页数
let searchNum = '';
let keyWord = '';
let projectNameParam = '';
export default class AssetInfoSupplementCard extends Component {

    constructor(props){
        super(props);
        this.state = {
            data: [],
            showFoot: 0,
        }
    }

    componentDidMount() {
        this.listener = DeviceEventEmitter.addListener('supplementScan', (code) => {
            searchNum = code;
            keyWord = '';
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })

        this.listener1 = DeviceEventEmitter.addListener('supplementSubmit', (text) => {
            searchNum = '';
            keyWord = text;
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })

        this.listener2 = DeviceEventEmitter.addListener('supplementChange', () => {
            searchNum = '';
            keyWord = '';
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })

        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })

        searchNum = '';
        keyWord = '';
        pageNo = 1;
        
        this.fetchData( pageNo, searchNum, keyWord );
    }

    componentWillUnmount() {
        //移除监听
        if (this.listener) {
          this.listener.remove();
        }
        if (this.listener1) {
            this.listener.remove();
        }
        if (this.listener2) {
            this.listener2.remove();
        }
        this.setState = (state,callback)=>{
            return;
        };
        projectNameParam = '';
    }


    changeProjectNameParam=(projectName)=>{
        projectNameParam = projectName;
    }

    fetchData = ( pageNo,searchNum, keyWord ) => {       
        RRCLoading.show();
        let params = {
            listType: 4,
            keyWord: keyWord,
            searchNum: searchNum,
            pageNum: pageNo,
            pageSize: 10,
            projectName:projectNameParam,
        }
        HttpUtil.post('listData', params)
            .then(result => { 
                if(result.httpCode == 200){ 
                    //console.log(result);
                    this.props.setCount(result.data.assetList.total);
                    let foot = 0;
                    totalPage = result.data.assetList.pages; //获取总页数
                    //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
                    if(pageNo>=totalPage){
                        
                        foot = 1;//listView底部显示没有更多数据了
                    }
                    if(pageNo == 1){
                        this.setState({
                            data:[],
                        });
                    }
                    this.setState({
                        data: [...this.state.data, ...result.data.assetList.records],
                        showFoot:foot,
                    });
                    RRCLoading.hide();
                }else{
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 3000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 3000);
            })
    }

    _onEndReached(){
        //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
             return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((pageNo!=1) && (pageNo>=totalPage)){
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({ showFoot:2 });
        //获取数据
        this.fetchData( pageNo, searchNum, keyWord );
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(10), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999', fontSize:getPixel(14), marginBottom:getPixel(5) }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(10), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999', fontSize:getPixel(14), marginBottom:getPixel(5) }}>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }


    detail = (id) => {
        this.props.navigation.navigate('AssetDetail', {
            id: id,
            isInfoSupplement:true,
            callBack: () => {
                this.setState({
                    data:[],
                });
                RRCLoading.setLoadingOptions({
                    text: '加载中',
                    loadingBackgroundColor: 'rgba(0,0,0,0.0)',
                    loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
                    loadingTextStyle: {}
                })
                pageNo = 1;
                searchNum = '';
                keyWord = '';
                this.fetchData(pageNo,searchNum, keyWord);
            }        
        });
    }

    renderItem(item){
        return (
            <View key={item.id} style={{ paddingLeft: getPixel(15), paddingRight: getPixel(15), marginTop: getPixel(10), paddingBottom: getPixel(20), paddingTop: getPixel(10), backgroundColor:'#FFF' }}>
                <TouchableOpacity onPress={() => this.detail(item.id_)}>
                    <View style={styles.cardTitle}>
                        <View style={styles.assetTag}>
                            <Text style={{ fontSize: getPixel(16), color:'#333' }}>
                                {item.assetName}
                            </Text>
                            <Text style={{ fontSize: getPixel(14), color:'#999' }}>
                                {item.rfidNo}
                            </Text>
                        </View>
                        <View style={styles.assetState}>
                            <Text style={[styles.assetStateText,{borderColor: item.statusShowColor,color: item.statusShowColor,}]}>
                                {item.statusName}
                            </Text>
                        </View>  
                    </View>
                    <View style={styles.cardInfo}>
                        <View style={styles.assetInfo}>
                            <View style={styles.assetInfoBasic}>
                                {/* <View style={styles.assetInfoBasicOwner}>
                                    <Text style={[{ fontSize: getPixel(16), color:'#333' }, item.manageUser ? {marginRight : getPixel(5)} : null]}>
                                        {item.manageUser}
                                    </Text>
                                    <Text style={ styles.assetInfoBasicDept }>
                                        {item.manageBranchName}
                                    </Text>
                                </View> */}
                                <Text style={{ fontSize: getPixel(14), color:'#999' }}>
                                    资产编号: {item.assetNo}
                                </Text>
                                <Text style={{ fontSize: getPixel(14), color:'#999' }}>
                                    SN: {item.serialNo}
                                </Text>
                            </View>
                            {/* <DashLine backgroundColor='#EEE' len={35} width={240} marginTop={getPixel(10)}  marginBottom={getPixel(10)} /> */}
                            <View style={styles.assetInfoOther}>
                            <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(245) }}>
                                        位置：{item.roomName}
                                    </Text>
                                    {/* <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(110) }}>
                                        U位：{item.startU} - {item.endU}
                                    </Text> */}
                                </View>
                                <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(245) }}>
                                        型号：{item.modelName}
                                    </Text>
                                    {/* <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(110) }}>
                                        机柜：{item.rackName}
                                    </Text> */}
                                </View>
                                <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(245) }}>
                                        类型：{item.typeName}
                                    </Text>
                                </View>
                            </View>
                        </View>
                        <View style={styles.assetImg}>
                            <Image source={ item.imgPath? { uri: item.imgPath } : require('../images/noimg.png') } style={ styles.img } />
                        </View>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    render() {
        return (
            <FlatList
                style={{ backgroundColor: '#F5F5F5', marginBottom: getPixel(40) }}
                data={this.state.data}
                renderItem={({item}) => this.renderItem(item)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={1}
                keyExtractor={(item, index) => index.toString()}
                ListFooterComponent={this._renderFooter.bind(this)}
            >
                <NavigationEvents onDidBlur={() => this.componentWillUnmount()}/>
            </FlatList>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },

    cardTitle: {
        flexDirection: 'row',
        borderBottomColor: '#EEEEEE',
        borderBottomWidth: getPixel(1),
    },
    cardInfo: {
        flexDirection: 'row',
        marginTop: getPixel(10),
    },
    assetTag: {
        width: getScreenWidth() - getPixel(110),
        height: getPixel(60),
        justifyContent: 'center',
    },
    assetInfo: {
        width: getScreenWidth() - getPixel(130),
        height: getPixel(130),
        justifyContent: 'center',
    },
    assetImg: {
        width: getPixel(100),
        height: getPixel(130),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetInfoBasic: {
        justifyContent: 'center',
    },
    assetInfoOther: {
        justifyContent: 'center',
    },
    assetInfoOtherText: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    assetInfoBasicOwner: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: getPixel(5),
    },
    assetInfoBasicDept: {
        fontSize: getPixel(12), 
        color:'#FFAA2E', 
        backgroundColor:'#FFF9EF',
        borderColor: '#FFAA2E',
        borderWidth: 1,
        padding: getPixel(2),
        paddingLeft: getPixel(4),
        height: getPixel(20),
    },
    img: {
        resizeMode: 'contain', 
        width: getPixel(100), 
        height: getPixel(100),
    },
    assetState: {
        width: getPixel(80),
        height: getPixel(60),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetStateText: {
        fontSize: getPixel(14), 
        width: getPixel(60),
        height: getPixel(30),
        borderWidth: 1,
        textAlign: 'center',
        lineHeight: getPixel(30),
        backgroundColor: '#eff3ff',
        borderRadius: 10,
    },
    footer:{
        flexDirection:'row',
        height: getPixel(24),
        justifyContent:'center',
        alignItems:'center',
        marginBottom:getPixel(10),
    },
});